package com.wcity.manage.web.community;

import com.wcity.manage.common.context.Constants;
import com.wcity.manage.common.context.SessionKey;
import com.wcity.manage.common.enums.Code;
import com.wcity.manage.common.enums.SaveImageType;
import com.wcity.manage.common.exception.CustomException;
import com.wcity.manage.common.utils.DwzUtil;
import com.wcity.manage.common.utils.JSONUtil;
import com.wcity.manage.common.utils.RespUtil;
import com.wcity.manage.common.utils.request.RequestUtil;
import com.wcity.manage.common.vo.community.social.SocialInfoVo;
import com.wcity.manage.common.vo.community.social.VisitRecordVo;
import com.wcity.manage.dao.dal.model.PageModel;
import com.wcity.manage.dao.model.Block;
import com.wcity.manage.dao.model.User;
import com.wcity.manage.dao.model.community.image.ImageUrl;
import com.wcity.manage.dao.model.community.social.VisitRecord;
import com.wcity.manage.service.BlockService;
import com.wcity.manage.service.RegisterService;
import com.wcity.manage.service.community.image.ImageService;
import com.wcity.manage.service.community.social.VisitRecordService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 社工走访记录
 * Created by hgg on 2016/12/21.
 */
@Controller
public class VisitRecordAct {

    private final static Logger log = LoggerFactory.getLogger(VisitRecordAct.class);

    @Autowired
    private VisitRecordService visitRecordService;
    @Autowired
    private BlockService blockService;
    @Autowired
    private ImageService imageService;
    @Autowired
    private RegisterService registerService;

    /**
     * 社工走访列表
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "community_visitRecord_list")
    public String visitRecordList( HttpServletRequest request, PageModel model,HttpServletResponse response ) {

        try {

            //【1】封装参数/参数校验
            Map<String, Object> requestMap = RequestUtil.getGetData(request);

            //【2】获取当前用户信息
            User user = (User)request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if( user == null ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            //【3】查询数据
            requestMap.put( "start", ( model.getPageNum() - 1) * model.getNumPerPage() );
            requestMap.put( "end", model.getNumPerPage());
            requestMap.put( "userId", user.getId() );
            List<VisitRecordVo> visitRecordVos = visitRecordService.visitRecordPageList(requestMap);

            //【4】查询总数量
            Integer totalVisitRecord = visitRecordService.totalVisitRecord(requestMap);
            model.setTotal( totalVisitRecord );

            request.setAttribute( "visitRecords", visitRecordVos );
            request.setAttribute( "pageModel", model );
            request.setAttribute( "buildTitle", requestMap.get( "buildTitle" ) );
            request.setAttribute( "blockId", requestMap.get( "blockId" ) );

            //【5】查询用户管理的小区列表
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put( "userId",user.getId() );
            List<Block> blocks = blockService.getAdminHaveBlockList( queryMap );
            request.setAttribute( "blocks",blocks );
        } catch ( Exception e ) {
            log.error( "查询社工走访列表异常:" + e.getMessage() );
        }
        return "community/visitrecord/list";
    }

    /**
     * 执行删除社工走访
     *
     * @param request
     */
    @RequestMapping(value = "delete_community_visitRecord")
    @ResponseBody
    public void deleteVisitRecord( HttpServletRequest request, HttpServletResponse response ) {

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "删除成功";
        try {

            //【1】校验参数
            Map<String, Object> requestMap = RequestUtil.getGetData( request );
            if (requestMap.get("id") == null) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "请选择一条记录", "", "", "", ""));
                return;
            }

            //【2】获取当前用户信息
            User user = (User)request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if( user == null ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return;
            }

            //【3】执行删除
            requestMap.put( "userId",user.getId() );
            Integer deleteNum = visitRecordService.deleteVisitRecord( requestMap );
            if ( deleteNum == 0 ) {
                code = Constants.STATUS_ERROR_DWZ;
                message = "删除失败";
            }
        } catch ( Exception e ) {
            log.error( "删除社工走访异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "删除失败";
        }
        RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(code, message, "", "", "", ""));
    }

    /**
     * 新增社工走访
     *
     * @param visitRecord
     * @param response
     */
    @RequestMapping(value = "save_add_community_visitRecord")
    @ResponseBody
    public void addVisitRecord( VisitRecord visitRecord, HttpServletResponse response, HttpServletRequest request ) {

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "保存成功";

        try {
            //【1】校验参数
            String imgUrl = request.getParameter( "imageUrl" );
            String blockIdStr = request.getParameter( "blockIdStr" );
            if ( StringUtils.isBlank( visitRecord.getBuildTitle() ) || StringUtils.isBlank( imgUrl ) || StringUtils.isBlank( blockIdStr ) ) {
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "参数错误", "", "", "", "" ) );
                return;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute(SessionKey.SESSION_USER_INFO);
            if ( user == null ) {
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return;
            }

            //【3】执行保存社工走访
            visitRecord.setUserId( user.getId() );
            visitRecordService.saveAddVisitRecord( visitRecord,imgUrl,blockIdStr );

        } catch ( Exception e ) {
            log.error( "保存社工走访异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "保存失败";
        }
        RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( code, message, "community_visitRecord_list", "", "closeCurrent", "" ) );
    }

    /**
     * 跳转到编辑社工走访页面
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "to_edit_community_visitRecord")
    public String visitRecordDetail( HttpServletRequest request, HttpServletResponse response ) {

        try {

            //【1】校验参数
            Map<String, Object> requestMap = RequestUtil.getGetData( request );
            if ( requestMap.get("id") == null ) {
                return null;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if ( user == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            //【3】查询社工走访数据
            requestMap.put("userId", user.getId());
            VisitRecordVo visitRecordVo = visitRecordService.visitRecordDetail( requestMap );
            request.setAttribute( "visitRecord", visitRecordVo );
            if ( visitRecordVo == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "数据不存在", "", "", "", ""));
                return null;
            }

            //【4】查询用户管理的未选择的小区列表
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put( "userId",user.getId() );
            queryMap.put( "id",requestMap.get("id") );
            String blocks = visitRecordService.blockIds( queryMap );
            queryMap.put( "notContain",1 );
            queryMap.put( "ids",blocks );
            List<Block> queryNotBlocks = blockService.getAdminHaveBlockList( queryMap );
            request.setAttribute( "blockNots",queryNotBlocks );

            //【5】查询用户管理的已选择的小区列表
            queryMap.put( "id",requestMap.get("id") );
            blocks = visitRecordService.blockIds( queryMap );
            queryMap.put( "id",null );
            queryMap.put( "notContain",null );
            queryMap.put( "contain",1 );
            queryMap.put( "ids",blocks );
            List<Block> queryBlocks = blockService.getAdminHaveBlockList( queryMap );
            request.setAttribute( "blocks",queryBlocks );

            //【6】查询封面
            Map<String,Object> queryImageMap = new HashedMap();
            queryImageMap.put( "referId",requestMap.get( "id" ) );
            queryImageMap.put( "saveType", SaveImageType.COMMUNITY_VISITRECORD );
            List<ImageUrl> imageUrls = imageService.images( queryImageMap );
            if( CollectionUtils.isNotEmpty( imageUrls ) ){
                request.setAttribute( "image",imageUrls.get(0) );
            }

        } catch ( Exception e ) {
            log.error( "查询社工走访失败: " + e.getMessage() );
            RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "查询失败", "", "", "", ""));
        }

        return "community/visitrecord/edit";
    }

    /**
     * 更新社工走访
     *
     * @param visitRecord
     * @param response
     */
    @RequestMapping(value = "save_edit_community_visitRecord")
    @ResponseBody
    public void updateVisitRecord( VisitRecord visitRecord, HttpServletResponse response, HttpServletRequest request ) {

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "更新成功";

        try {

            //【1】校验参数
            String imageUrl = request.getParameter( "imageUrl" );
            String blockIdStr = request.getParameter( "blockIdStr" );
            if ( StringUtils.isBlank( visitRecord.getBuildTitle() ) || StringUtils.isBlank( imageUrl )
                    || StringUtils.isBlank( blockIdStr ) || StringUtils.isBlank( visitRecord.getBuildContent() ) ) {
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "参数错误", "", "", "", "" ) );
                return;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if (user == null) {
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return;
            }

            //【3】执行更新社工走访
            visitRecord.setUserId( user.getId() );
            visitRecordService.saveUpdateVisitRecord( visitRecord,imageUrl,blockIdStr );

        } catch ( Exception e ) {
            log.error( "更新社工走访异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "更新失败";
        }
        RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( code, message, "community_visitRecord_list", "", "closeCurrent", "" ) );
    }

    /**
     * 跳转到添加社工走访的页面
     * @return
     */
    @RequestMapping(value = "to_add_community_visitRecord")
    public String toAddVisitRecord( HttpServletResponse response,HttpServletRequest request ){

        try {

            //【1】获取当前用户信息
            User user = (User)request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if( user == null ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            //【2】查询用户管理的小区列表
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put( "userId",user.getId() );
            String blocks = visitRecordService.blockIds( queryMap );
//            queryMap.put( "notContain",1 );
            queryMap.put( "ids",blocks );
            List<Block> queryBlocks = blockService.getAdminHaveBlockList( queryMap );
            request.setAttribute( "blocks",queryBlocks );

        }catch ( Exception e ){
            log.error( "跳转到办事指南页面异常：" + e.getMessage() );
        }
        return "community/visitrecord/add";
    }

    /**
     * 跳转到社工走访详情页面
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "to_detail_community_visitRecord")
    public String visitRecordDetailPage( HttpServletRequest request, HttpServletResponse response ) {

        try {

            //【1】校验参数
            Map<String, Object> requestMap = RequestUtil.getGetData( request );
            if ( requestMap.get("id") == null ) {
                return null;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if ( user == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            //【3】查询社工走访数据
            requestMap.put("userId", user.getId());
            VisitRecordVo visitRecordVo = visitRecordService.visitRecordDetail( requestMap );
            request.setAttribute( "visitRecord", visitRecordVo );
            if ( visitRecordVo == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "数据不存在", "", "", "", ""));
                return null;
            }

            //【4】查询用户管理的已选择的小区列表
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put( "userId",user.getId() );
            queryMap.put( "id",requestMap.get("id") );
            String blocks = visitRecordService.blockIds( queryMap );
            queryMap.put( "id",null );
            queryMap.put( "notContain",null );
            queryMap.put( "contain",1 );
            queryMap.put( "ids",blocks );
            List<Block> queryBlocks = blockService.getAdminHaveBlockList( queryMap );
            request.setAttribute( "blocks",queryBlocks );

            //【5】社工查看封面
            Map<String,Object> queryImageMap = new HashMap<>();
            queryImageMap.put( "referId",requestMap.get("id") );
            queryImageMap.put( "saveType", SaveImageType.COMMUNITY_VISITRECORD );
            List<ImageUrl> imageUrls = imageService.images( queryImageMap );
            request.setAttribute( "imageUrls",imageUrls );
        } catch ( Exception e ) {
            log.error( "查询社工走访失败: " + e.getMessage() );
            RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "查询失败", "", "", "", ""));
        }

        return "community/visitrecord/detail";
    }

    /**********************************************************H5端****************************************************************/

    /**
     * 社工走访列表
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "community_visitrecord_list_h5")
    @ResponseBody
    public Object socialInfoListH5( HttpServletRequest request, PageModel model,HttpServletResponse response ) {

        try {

            //【1】校验参数
            Map<String,Object> requestMap = new HashedMap();
            String surveyId = request.getParameter( "surveyId" );
            if( StringUtils.isBlank( surveyId ) ){
                throw new CustomException( Constants.PARAMETER_ERROR, Code.ERROR );
            }

            //【2】获取当前用户信息
//            Map<String,Object> userMap = (Map<String,Object>)registerService.registerInfo( registerId );
//            if( userMap == null || userMap.get( "blockId" ) == null ){
//                throw new CustomException( "用户信息不存在", Code.ERROR );
//            }

            //【2】查询数据
            requestMap.put( "start", ( model.getPageNum() - 1) * model.getNumPerPage() );
            requestMap.put( "end", model.getNumPerPage() );
            requestMap.put( "blockId",Integer.parseInt( surveyId ) );
            requestMap.put( "saveType",SaveImageType.COMMUNITY_VISITRECORD );
            List<VisitRecordVo> visitRecordVos = visitRecordService.visitRecordPageList( requestMap );

            //【3】查询总数量
            Integer totalWorkGuide = visitRecordService.totalVisitRecord( requestMap );
            model.setTotal( totalWorkGuide );

            Map<String,Object> map = JSONUtil.getSuccessJson();
            map.put( "data",visitRecordVos );
            map.put( "pageModel",model );
            return map;
        } catch ( Exception e ) {
            log.error( "查询社工报名列表异常:" + e.getMessage() );
            return null;
        }
    }

    /**
     * 社工走访详情（H5）
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "community_visitrecord_detail_h5")
    @ResponseBody
    public Object workGuideDetailH5( HttpServletRequest request, HttpServletResponse response ) {

        try {

            //【1】校验参数
            Map<String,Object> requestMap = new HashedMap();
            String surveyId = request.getParameter( "surveyId" );
            String id = request.getParameter( "id" );
            if( StringUtils.isBlank( surveyId ) || StringUtils.isBlank( id ) ){
                throw new CustomException( Constants.PARAMETER_ERROR, Code.ERROR );
            }

            //【2】获取当前用户信息
//            Map<String,Object> userMap = (Map<String,Object>)registerService.registerInfo( registerId );
//            if( userMap == null || userMap.get( "blockId" ) == null ){
//                throw new CustomException( "用户信息不存在", Code.ERROR );
//            }

            //【3】查询社工信息详情
            requestMap.put( "id", Integer.parseInt( id ) );
            requestMap.put( "blockId",Integer.parseInt( surveyId ) );
            VisitRecordVo visitRecordVo = visitRecordService.visitRecordDetail( requestMap );
            if ( visitRecordVo == null ) {
                return null;
            }
            //【5】社工查看封面
            Map<String,Object> queryImageMap = new HashMap<>();
            queryImageMap.put( "referId",requestMap.get("id") );
            queryImageMap.put( "saveType", SaveImageType.COMMUNITY_VISITRECORD );
            List<ImageUrl> imageUrls = imageService.images( queryImageMap );

            Map<String,Object> map = JSONUtil.getSuccessJson();
            map.put( "data",visitRecordVo );
            if( CollectionUtils.isNotEmpty( imageUrls ) ){
                map.put( "image",imageUrls.get( 0 ) );
            }
            return map;
        } catch ( Exception e ) {
            log.error( "查询社工走访失败: " + e.getMessage() );
            return null;
        }

    }
}
